var api = frameElement.api, oper = api.opener;
var config=oper.parent.CONFIG;
var system = oper.parent.SYSTEM;
if(config == undefined){
	var config=oper.parent.parent.CONFIG;
	var system=oper.parent.parent.SYSTEM;
}
var queryConditions = {
		searchContent: ''
	};
var needVaildateStock = $("#needVaildateStock").val()=='1'?true:false;
var fromJsp = $("#fromJsp").val();
var needVaildateGetAmount = fromJsp == 'modify'?true:false;

var detailurl = config.BASEPATH+"shop/gift/temp_loadproduct";
var saveUrl = config.BASEPATH+'shop/gift/temp_save';


$.fn.subtext=function(value,count,txt){	
	if (value.length>count){
		if (txt==null){txt='..'}
		$(this).text(value.substring(0,count)+txt);
		$(this).attr('title',value); 
	}else{
		$(this).text(value);
	}    
};    

$.fn.subval=function(value,count){	
	if (value.length>count){
		$(this).val(value.substring(0,count));
		$(this).attr('title',value); 
	}else{
		$(this).val(value);
	}    
}; 
var Utils = {
	formatMoneyByRetailPriceLimit:function(value){
    	if(!hasRetailPriceLimit){
    		return '***';
    	}
    	return parseFloat(value).toFixed(2);
    }
};

var handle = {
	save:function(next){
		var jsonObject=updateDatas.get();
		var jsonString=JSON.stringify(updateDatas.get());
		if (jsonObject.length>0){
			var pd_code = $("#currentPdCode").val();
			$('#btnSave').attr('disabled','disabled');
			$('#btnSaveAndNext').attr('disabled','disabled');
			$.ajax({
				type:"POST",
				url:saveUrl,
				data:{data:Public.encodeURI(jsonString),pd_code:pd_code,fromJsp:fromJsp},
				async:true,
				cache:false,
				dataType:"json",
				success:function(data){
					if(undefined != data && data.stat == 200){
						updateDatas.clear();
						Public.tips({type: 3, content : '保存成功！'});
						W.isRefresh=true;
						api.close();
					}else{
						Public.tips({type: 1, content : '保存失败！'});
					}
					$('#btnSave').removeAttr('disabled');
					$('#btnSaveAndNext').removeAttr('disabled');
				}
			});
		}else{
			api.close();
		}
	}
};
var chkVaildateStock,chkRealStock,chkUseableStock;
var columnsOriginal = null;
var dataValueOriginal = null;

var THISPAGE = {
	init:function (data){
		chkVaildateStock=$("#chkVaildateStock").cssCheckbox();
		chkRealStock=$("#chkRealStock").cssCheckbox();
		chkUseableStock=$("#chkUseableStock").cssCheckbox();
		$("#chkUseableStock").css('display','none');
		if(needVaildateStock){//是否需要验证库存
			$("#chkVaildateStock").css('display','');
		}else{
			$("#chkVaildateStock").css('display','none');
		}
		$("#chkVaildateStock").css('display','none');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		if(realStock && useableStock){
			$('#spanDescribe').text('注:实际库存/可用库存/录入数量');
		}else if(realStock){
			$('#spanDescribe').text('注:实际库存/录入数量');
		}else if(useableStock){
			$('#spanDescribe').text('注:可用库存/录入数量');
		}else{
			$('#spanDescribe').text('注:录入数量');
		}
		var pd_code = $("#currentPdCode").val();
		this.loadDetailGrid(pd_code);
		this.addEvent();	
	},
	initDom: function(data){
		var _self = this;
		this.$sizeDetailGrid=$('#sizeDetail');
		this.selectCell={iRow:0,iCol:0,rowid:0,value:''};
		$('#txtNo').text(product.no);
		$('#txtName').text(product.name);
		$('#txtTpName').text(product.tp_name);
		$('#txtBdName').text(product.bd_name);
		$('#txtSSName').text(product.season);
		$('#txtYear').text(product.year);
		$('#txtUnitPrice').text(product.sell_price);
		$('#txtUnitPriceShow').val(PriceLimit.formatBySell(product.sell_priceShow));
		$('#txtSortPrice').text(product.sort_price);
		$('#txtSortPriceShow').val(PriceLimit.formatByDistribute(product.sort_priceShow));
		if(product.img_path != null && product.img_path != ''){
			$("#ProductPhoto").attr("src",$("#ftpURL").val()+product.img_path);
		}else{
			$("#ProductPhoto").attr("src",config.BASEPATH+'resources/grid/images/nophoto.png');  
		}
	},
	setCellSelected:function(allotAmount){
		var selectCell=this.selectCell;
		var value=$('#grid').getCell(selectCell.iRow,selectCell.iCol);
		var arrValue=value.split('/');
		if (allotAmount!=''){
			if (arrValue[0]==''){
				arrValue[0]='0';
			}
			arrValue[0]+='/'+allotAmount;
		}
		this.$grid.setCell(selectCell.iRow,selectCell.iCol,arrValue[0]);
	},
	buildDetailUrlParams:function(pd_code){
		var params="pd_code="+pd_code;
		if(api.data.gil_shop_code != undefined){
			params += "&gil_shop_code="+api.data.gil_shop_code;
		}
		return params;
	},
	loadDetailGrid:function(pd_code){
		$("#btnSave").css('display','');
    	$("#btnExit").css('display','');
    	$("#ProductInfo").css('display','');
		$.ajax({
			type:"POST",
			url:detailurl+'?'+THISPAGE.buildDetailUrlParams(pd_code)+'&Exists=1',
			cache:false,
			dataType:"json",
			success:function(dataValue){
				if(dataValue != ""){
					product=dataValue.product;
					$('#sizeDetail').GridUnload();
					THISPAGE.initDom();
					THISPAGE.initDetailGrid(dataValue.sizes,dataValue.data);	
				}
			}
		});
	},
	initDetailGrid:function(columns,dataValue){
		$("#priceModifyed").val('')
		updateDatas.clear();//清空json中临时数据
		columnsOriginal = columns;
		dataValueOriginal = dataValue;
		var grid=this.$sizeDetailGrid;
		var _self=this;
		var gridWH = Public.setGrid();
		var colModel = [
	    	{label:'颜色', name: 'cr_name',index: '', width: 70,fixed:true},
	    	{name:'cr_code',hidden:true},
	    	{label:'杯型', name: 'br_name',index: '', width: 40,fixed:true},
	    	{name:'br_code',hidden:true},
	    	{name:'id',hidden:true}
	    ];
		if (columns!=null&&columns.length>0){
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({name: columns[i].code
					,label:columns[i].name
					, index: columns[i].code
					, width: 60
					,editable:true 
				});
			}	
		}
		colModel.push({label:'小计',name:'totalAmount', width: 60});
		grid.jqGrid({
			datatype: 'json',
			//autowidth: true,
			width:765,
			//height: gridWH.h-35,
			height:250,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			viewrecords: true,
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			shrinkToFit:false,
            cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
            userDataOnFooter: true,
            triggerAdd:false,
			jsonReader: {
				root: 'rows',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data){
				
			},
			loadError: function(xhr, status, error){
			},
			formatCellTitle:function(val,iRow, iCol){
				var title='';
				var key= colModel[iCol-1].name;
				var value = dataValueOriginal.rows[iRow-1][key];
				value = $.trim(value);
				if(value == ''){
					title = '';
				}
				var arrValue=value.split('/');
				if(arrValue !=null && arrValue != '' && arrValue.length > 0){
					title =  "实际："+arrValue[0];
				}
				if(needVaildateGetAmount){
					var keyPub= colModel[iCol-1].name+'_pub';
					var pubAmount = dataValueOriginal.rows[iRow-1][keyPub];
					if(pubAmount != undefined && pubAmount != ''){
						if(title == ''){
							title = "已发布："+pubAmount;
						}else{
							title += "<br/>已发布："+pubAmount;
						}
					}
					var keyGet= colModel[iCol-1].name+'_get';
					var getAmount = dataValueOriginal.rows[iRow-1][keyGet];
					if(getAmount != undefined && getAmount != ''){
						if(title == ''){
							title = "已兑换："+getAmount;
						}else{
							title += "<br/>已兑换："+getAmount;
						}
					}
				}
				return title;
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){//切换输入框前处理
				var value=grid.getCell(iRow,iCol);
				var selectCell=_self.selectCell;
				selectCell.rowid=rowid;
				selectCell.iRow=iRow;
				selectCell.iCol=iCol;
				selectCell.value=value;
				var arrValue=value.split('/');
				var inputValue;
				
				var realStock = chkRealStock.chkVal().join() ? true : false;
				var useableStock = chkUseableStock.chkVal().join() ? true : false;
				if(realStock && useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
						selectCell.value2=arrValue[2];
					}else{
						selectCell.value0=0;
						selectCell.value1=0;
						selectCell.value2='';
					}	
					inputValue=selectCell.value2;
				}else if(realStock || useableStock){
					if (arrValue!=''){
						selectCell.value0=arrValue[0];
						selectCell.value1=arrValue[1];
					}else{
						selectCell.value0=0;
						selectCell.value1='';
					}
					inputValue=selectCell.value1;
				}else{
					selectCell.value0=arrValue[0];
					inputValue=selectCell.value0;
				}
				return inputValue;
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				var selectCell=_self.selectCell;
				if (Validate.amount(value)){
					if(needVaildateGetAmount){
						var keyPub= colModel[iCol-1].name+'_pub';
						var pubAmount = dataValueOriginal.rows[iRow-1][keyPub];
						var keyGet= colModel[iCol-1].name+'_get';
						var getAmount = dataValueOriginal.rows[iRow-1][keyGet];
						if(getAmount != undefined && getAmount != ''){
							if(parseInt(value)+parseInt(pubAmount)<parseInt(getAmount)){
								Public.tips({type: 2, content : '总发布数量不能小于已领取数量！'});
								return _self.selectCell.value;
							}
						}
					}
					//验证库存
					var vaildateStock=chkVaildateStock.chkVal().join() ? true : false;
					var realStock = chkRealStock.chkVal().join() ? true : false;
					var useableStock = chkUseableStock.chkVal().join() ? true : false;
					if(vaildateStock){
						var originalValue = dataValueOriginal.rows[iRow-1][colModel[iCol-1].name];//从原始数据中取得实际库存的值
						originalValue = $.trim(originalValue);
						var stockAmount = 0;
						var arrValue=originalValue.split('/');
						if(arrValue != null && arrValue != '' && arrValue.length > 0){
							stockAmount = arrValue[0];
						}
						if(parseInt(value)>parseInt(stockAmount)){
							Public.tips({type: 2, content : '库存不足！'});
							if(realStock && useableStock){
								value = _self.selectCell.value2;
							}else if(realStock || useableStock){
								value = _self.selectCell.value1;
							}else{
								value = _self.selectCell.value0;
							}
						}
					}
					value=value==0?'':value;
					
					var realStock = chkRealStock.chkVal().join() ? true : false;
					var row=grid.getRowData(rowid);
					var unitPrice = $("#txtUnitPriceShow").val();
					if(isNaN(unitPrice)){
						unitPrice = product.retailPrice;
					}
					var sortPrice = $("#txtSortPriceShow").val();
					if(isNaN(sortPrice)){
						sortPrice = product.sort_price;
					}
					var updateData={
						no:product.no
//						,unit_name:product.unit_name
						,cost_price:product.cost_price
						,unitPrice:unitPrice
						,sortPrice:sortPrice
						,sell_price:product.sell_price
						,szg_code:product.szg_code
						,cr_code:row.cr_code
						,sz_code:colModel[iCol-1].name
						,br_code:row.br_code
						,backStockAmount:selectCell.value0
						,amount:value==''?0:value
					};
					
					if(needVaildateGetAmount){
						var keyPub= colModel[iCol-1].name+'_pub';
						var pubAmount = dataValueOriginal.rows[iRow-1][keyPub];
						if(pubAmount != undefined && pubAmount != ''){
							updateData.pubAmount = pubAmount;
						}else{
							updateData.pubAmount = 0;
						}
					}
					
					var newValue;
					if(realStock && useableStock){
						updateData.initAmount=selectCell.value2==''?0:selectCell.value2;
						if (selectCell.value0!=0
								||selectCell.value1!=0||value!=''){
							newValue=selectCell.value0+'/'+selectCell.value1+'/'+value;	
						}else{
							newValue='';
						}
					}else if(realStock || useableStock){
						updateData.initAmount=selectCell.value1==''?0:selectCell.value1;
						if (selectCell.value0!=0||value!=''){
							newValue=selectCell.value0+'/'+value;	
						}else{
							newValue='';
						}
					}else{
						updateData.initAmount=selectCell.value0==''?0:selectCell.value0;
						newValue = value;
					}
					updateDatas.add(updateData);
					return newValue;
				}else{ 
					return _self.selectCell.value;
				}
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				THISPAGE.gridTotal();
				var maxRow = dataValue.rows.length;
				var maxCol = columns.length+5;
				var event = window.event||arguments[0];
				if(event.keyCode === 13 && ((iRow === maxRow && iCol === maxCol) || event.ctrlKey)){
					if($("#btnSaveAndNext").css('display') != 'none'){
						$('#btnSaveAndNext').click();
					}else{
						$('#btnSave').click();
					}
				}
			},
			plusKeyDown:function(){
				$('#btnSave').click();
			}
	    });
		$('#sizeDetail').clearGridData();
		if (dataValue!=null){		
			var isBraSize=false;
			var grid=$('#sizeDetail');
			for(var i=0;i< dataValue.rows.length;i++){
				grid.jqGrid('addRowData', i + 1, dataValue.rows[i]);
				if (!isBraSize&&dataValue.rows[i].br_code!=''){
					isBraSize=true;
				}
			}
			if (isBraSize) {
				grid.showCol("br_name");
            }else{
            	grid.hideCol("br_name");
            }
	    	THISPAGE.reloadDetailGridData();
		}
	},
	reloadDetailGridData:function(){
		var grid=$('#sizeDetail')
		,rows=grid.getRowData()
		,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue = null;
				var originalValue = null;
				if(row[key] != null && row[key] != ''){
					arrValue=row[key].split('/');
				}
				if(dataValueOriginal.rows[rowIndex][key] != null && dataValueOriginal.rows[rowIndex][key] != ''){
					originalValue = dataValueOriginal.rows[rowIndex][key].split('/');
				}
				var newValue = '';
				
				if(originalValue != null && originalValue != '' && originalValue.length > 0){
					if(originalValue[0] != null && originalValue[0] != '' && realStock){
						newValue += originalValue[0]+'/';
					}					
					if(originalValue[1] != null && originalValue[1] != '' && useableStock){
						newValue += originalValue[1]+'/';	
					}
				}else{
					if(realStock){
						newValue += '0/';
					}
					if(useableStock){
						newValue += '0/';
					}
				}
				
				if (arrValue != null && arrValue != '' && arrValue.length > 0){
					newValue += arrValue[arrValue.length-1]
				}
				rows[rowIndex][key] = newValue;
			}
		}
		grid.clearGridData();
		for(var i=0;i< rows.length;i++){
			grid.jqGrid('addRowData', i + 1, rows[i]);
		}
		THISPAGE.gridTotal();
	},
	gridTotal:function(iRow,iCol){
		
		var grid=$('#sizeDetail')
			,rows=grid.getRowData()
			,rowFoot=grid.footerData()
			,colModel=grid.getGridParam('colModel');
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var total1=0,total2=0,total3=0;
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			
			if(realStock && useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2+'/'+total3));
			}else if(realStock || useableStock){
				grid.setCell(row.id,'totalAmount',(total1+'/'+total2));
			}else{
				grid.setCell(row.id,'totalAmount',(total1));
			}
		}
		rows=grid.getRowData();
		for ( var colIndex = 6; colIndex < colModel.length; colIndex++) {
			var total1=0,total2=0,total3=0;
			var key= colModel[colIndex].name;
			for ( var index = 0; index < rows.length; index++) {
	    		var row=rows[index];
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if(arrValue[0] != null && arrValue[0]!='' && !isNaN(arrValue[0])){
						total1+=parseInt(arrValue[0]);	
					}					
					if(arrValue[1] != null && arrValue[1]!='' && !isNaN(arrValue[1])){ 
						total2+=parseInt(arrValue[1]);
					}
					if(arrValue[2] != null && arrValue[2]!='' && !isNaN(arrValue[2])){
						total3+=parseInt(arrValue[2]);	
					}
				}
			}
			if(realStock && useableStock){
				if (total1==0&&total2==0&&total3==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2+'/'+total3)+'"}';
				}	
			}else if(realStock || useableStock){
				if (total1==0&&total2==0){
					json= '{"'+colModel[colIndex].name+'":""}';
				}else{
					json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2)+'"}';
				}
			}else{
				json= '{"'+colModel[colIndex].name+'":"'+(total1)+'"}';
			}
			var jj=eval('('+json+')');
			grid.footerData("set",jj);
		}
		grid.footerData("set",{colorName:'合计：'});
	},
	initTip:function(){
		var realStock = chkRealStock.chkVal().join() ? true : false;
		var useableStock = chkUseableStock.chkVal().join() ? true : false;
		if(realStock && useableStock){
			$('#spanDescribe').text('注:实际库存/可用库存/录入数量');
		}else if(realStock){
			$('#spanDescribe').text('注:实际库存/录入数量');
		}else if(useableStock){
			$('#spanDescribe').text('注:可用库存/录入数量');
		}else{
			$('#spanDescribe').text('注:录入数量');
		}
	},
	addEvent:function(){
		var _self = this;
		//实际库存点击
		$('#chkRealStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		//可用库存点击
		$('#chkUseableStock').click(function(){
			THISPAGE.initTip();
			THISPAGE.reloadDetailGridData();
		});
		//保存
		$('#btnSave').on('click', function(e){
			handle.save();
		});
		//保存并下一条
		$('#btnExit').on('click', function(e){
			api.close();
		});
	}
};

var updateDatas={
	datas:[]
	,add:function(updateData){
		var isExists=false;
		for ( var i = 0; i < this.datas.length; i++) {
			var data=this.datas[i];
			if (data.no==updateData.no
				&&data.colorCode==updateData.colorCode
				&&data.sizeCode==updateData.sizeCode
				&&data.braSizeCode==updateData.braSizeCode
				){
				data.amount=updateData.amount;
				isExists=true;
				break;
			}
		}
		if (!isExists){
			this.datas.push(updateData);
		}
	},
	get:function(){
		var datas=this.datas;
		var data;
		//去除没有更改的数据
		for ( var i = 0; i < datas.length; i++) {
			data=datas[i];
			if(needVaildateGetAmount){
				if (data.initAmount==='' || (data.initAmount === 0 && data.amount != 0)){
					if(data.pubAmount != '' && data.pubAmount > 0){
						data.operateType='update';
					}else{
						data.operateType='add';
					}
				}else if (data.initAmount==data.amount){
					datas.splice(i,1);
					i--;
				}else{
					data.operateType='update';
				}
			}else{
				if (data.initAmount==='' || (data.initAmount === 0 && data.amount != 0)){
					data.operateType='add';
				}else if (data.initAmount==data.amount){
					datas.splice(i,1);
					i--;
				}else{
					data.operateType='update';
				}
			}
			
		}
		if (datas.length>0){
			oper.isRefresh=true;
		}
		return datas;
	},
	clear:function(){
		this.datas = [];
	}
};

var Validate={
	amount:function(value){
		var reg='';
		if(needVaildateGetAmount){
			reg=/^(-)?[0-9]*[0-9][0-9]*$/;
		}else{
			reg=/^[0-9]*[0-9][0-9]*$/;	
		}
		return reg.test(value);
	}
}
THISPAGE.init();
